from django.http import JsonResponse
from django.views import View
from rest_framework_jwt.settings import api_settings

from user.models import SysUser


# Create your views here.
class TestView(View):
    # 视图类
    def get(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')  # 获取请求头中的token值
        print("token:", token)
        if token != None and token != '':
            # 获取请求的的视图函数
            # 1.查询sys_user表的全部数据
            sys_users = SysUser.objects.all()
            userList_dict = sys_users.values()  # 将查询集对象转换成字典
            print("userList_dict:", userList_dict)
            userList = list(userList_dict)  # 将查询集对象转换成列表
            print("userList:", userList)
            return JsonResponse({'code': 200, 'info': '测试！', 'data': userList})
        else:
            return JsonResponse({'code': 403, 'info': '无法访问，请登录！'})


class JwtTestView(View):
    def get(self, request):
        # jwt-token生成流程：
        # 1.安装djangorestframework-jwt 模块
        # 2.在登录view视图模块中导入api_settings模块
        # 3.创建jwt_payload_handler对象和jwt_encode_handler对象
        # 4.使用jwt_payload_handler对象获取当前登录用户信息和jwt_encode_handler对象再生成token值即可

        sys_users = SysUser.objects.get(username="admin", password="123456")
        print("sys_users:", sys_users)

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 获取jwt_payload_handler
        print("jwt_payload_handler:", jwt_payload_handler)

        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 获取jwt_encode_handler
        print("jwt_encode_handler:", jwt_encode_handler)

        payload = jwt_payload_handler(sys_users)  # 获取payload
        print("payload:", payload)

        token = jwt_encode_handler(payload)  # 获取token
        print("token:", token)

        return JsonResponse({'code': 200, 'info': '测试！', 'token': token})
